﻿using Common;
using Http;
using Log4_Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NoticeCorpWechat.interfaces;
using NoticeCorpWechat.result;
using System;
using System.Diagnostics.CodeAnalysis;

namespace NoticeCorpWechat
{
    public static class CorpWechat
    {
        public static IServiceCollection AddCorpWechat([NotNull] this IServiceCollection services)
        {
            services.AddHttpClients();
            services.AddScoped(typeof(IAccessTokenHelper), typeof(AccessTokenHelper));
            services.AddScoped(typeof(IMessageHelper), typeof(MessageHelper));
            return services;
        }
    }
    public class AccessTokenHelper: IAccessTokenHelper
    {
        IHttpClientHelper _httpClientHelper;
        ILogger _ILogger;
        public AccessTokenHelper(IHttpClientHelper httpClientHelper, ILogHelper logHelper)
        {
            _httpClientHelper = httpClientHelper;
            _ILogger = logHelper.GetLogger();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="corpid"></param>
        /// <param name="corpsecret"></param>
        /// <returns></returns>
        public string Get_AccessToken(string corpid, string corpsecret)
        {
            try
            {
                var result = _httpClientHelper.Get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret + "");
                if (result.NotNullOrEmpty())
                {
                    var res = result.JsonToObject<TokenResult>();
                    if (res.errcode == 0)
                        return res.ToJson();
                }
            }
            catch (Exception ex)
            {
                _ILogger.LogError(ex.Message + ex.StackTrace);
            }
            return null;
        }
    }
}
